import axios from "axios";

const baseUrl = import.meta.env.VITE_BASE_URL

const server = axios.create({
    baseURL:baseUrl,
    timeout:300000
})

server.interceptors.request.use(async(config)=>{
    let data = {}
    // 设置请求头位application/json
    config.headers = {"Content-Type":'application/json;'}
    // 从浏览器本地取出token令牌
    const token = await localStorage.getItem('token')
    // 判断本地token是否存在，存在则携带至请求头
    if(token && token != 'undefined'){
        config.headers["token"] = JSON.parse(token)
    }
    if(config.data){
        data = config.data;
        if(data.file){
            config.headers = {
                "Content-Type":"multipart/form-data;"
            }
            // 请求偷带x-token   --暂时不明确后端需求字段位token或者x-token
            if(token&&token !=="undefined"){
                config.headers['x-token'] = JSON.parse(token)
            }
            // 创建formData
            let formData = new FormData()
            // 将带文件的字段放入formdata
            formData.append('file',data.file)
            config.data = formData
        }else{
            config.data = JSON.stringify(data)
        }
    }
    return config
},function(err){
    Promise.reject(err)
})

server.interceptors.response.use(
    // 响应拦截
    async (response) => {
        // 拦截的响应code为3003则为token过期需要重新登录
      if (response.data.code == 3003 || response.data.code == 2000) {
        ElMessage.info(response.data.code == 3003?"登录过期":'用户不存在');
        localStorage.removeItem("token");
        window.location.href = "/login";
      }
      return response;
    },
    (err) => {
      if (err.response.data.code == 3003 || response.data.code == 2000) {
        ElMessage.info(response.data.code == 3003?"登录过期":'用户不存在');
        localStorage.removeItem("token");
        window.location.href = "/login";
      }
      return err;
    }
  );


  export default server